package com.k.ums.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.k.ums.config.property.DruidProperties;
import com.k.ums.context.Ums;
import com.k.ums.datasource.DynamicDataSource;
import com.k.ums.enums.DataSourceType;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Description:
 * @Author: kt
 * @CreateTime: 2022/1/8
 */
@Configuration
public class DruidConfig {

    @Bean
    @ConfigurationProperties("spring.datasource.druid.master")
    public DataSource masterDataSource(DruidProperties druidProperties) {
        return druidProperties.dataSource();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.slave")
    @ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enable", havingValue = "true")
    public DataSource slaveDataSource(DruidProperties druidProperties) {
        return druidProperties.dataSource();
    }

    @Bean("dynamicDataSource")
    @Primary
    public DynamicDataSource dynamicDataSource(DataSource masterDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>(2);
        targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
        Environment environment = Ums.getUmsContext().getDelegator().getEnvironment();
        boolean slaveEnable = environment.getProperty("spring.datasource.druid.slave.enable",Boolean.class,false);
        if (slaveEnable) {
            DruidDataSource slaveDataSource = Ums.getUmsContext().getBean("slaveDataSource", DruidDataSource.class);
            targetDataSources.put(DataSourceType.SALVE.name(), slaveDataSource);
        }
        return new DynamicDataSource(masterDataSource, targetDataSources);
    }
}
